import { Box, Button, Input, Paper, TextField } from "@mui/material";
import { useSnackbar } from "notistack/dist";
import React, { useEffect, useRef, useState } from "react";
import MyButton from "../../components/MyButton";
import RandomButton from "../../components/RandomButton";
import "./main.css";
import Pillar from "./Pillar";

export default function Bubble(props) {
  const [numbers, setNumbers] = useState([]);
  const [color, setColor] = useState([]);
  const [pos, setPos] = useState([]);
  const [ipt, setIpt] = useState();
  const { msg, setMsg } = props;
  const [tnumbers, setTnumbers] = useState([]);
  // const [mount.current, setMount] = useState(true);
  const mount = useRef(false);
  const [isSorting, setIsSorting] = useState(false);

  const sleep = (time) => {
    // console.log(props.speed);

    return new Promise(function (resolve) {
      setTimeout(resolve, time * props.speed);
    });
  };

  useEffect(() => {
    var tmp = [];
    var mx = 0;
    for (var i in numbers) {
      if (numbers[i] > mx) mx = numbers[i];
    }
    for (var i in numbers) {
      tmp.push((380 / mx) * numbers[i]);
    }

    setTnumbers(tmp);
  }, [numbers]);

  var tnum,
    tpos,
    tcolor,
    tmsg = msg;

  useEffect(() => {
    setMsg({
      sentence: "冒泡排序",
      sT: 0,
      cT: 0,
      tot: 0,
    });
    mount.current = true;
    return () => (mount.current = false);
  }, []);
  const { enqueueSnackbar } = useSnackbar();

  const change = async () => {
    // console.log(ipt);
    if (isSorting) {
      enqueueSnackbar("正在排序", { variant: "warning" });
      return;
    }
    if (ipt == null) {
      enqueueSnackbar('请输入以","分隔的正整数', { variant: "error" });
      return;
    }
    tnum = ipt.split(",").map((val) => {
      return +val;
    });

    for (var i in tnum) {
      if (isNaN(tnum[i]) || tnum[i] == 0) {
        enqueueSnackbar('请输入以","分隔的正整数', { variant: "error" });
        return;
      }
    }

    setIsSorting(true);
    setNumbers(tnum);

    var tmp = ipt.split(",").length;

    tmsg = { sentence: "冒泡排序", cT: 0, sT: 0, tot: tmp };
    if (mount.current)
      setMsg({
        ...tmsg,
      });
    else return;
    tpos = [];
    tcolor = [];

    for (var i = 0; i < tmp; ++i) {
      tpos.push(i);
      tcolor.push(1);
    }

    setPos(tpos);
    setColor(tcolor);
    // console.log(props.speed);

    await sleep(600);
    await solve();
    setIsSorting(false);
  };

  const solve = async () => {
    var tmp1 = [...tpos];
    var tmp3 = [...tpos];

    const len = tnum.length;
    for (var i = 0; i < len; ++i) {
      for (var j = 0; j < len - i - 1; ++j) {
        await sleep(600);

        setColor(
          tcolor.map((val, index) => {
            return tmp3[index] == j || tmp3[index] == j + 1
              ? 2
              : tmp3[index] > len - i - 1
              ? 3
              : 1;
          })
        );

        // console.log(msg);
        tmsg = {
          ...tmsg,
          cT: tmsg.cT + 1,
          sentence: "比较" + tnum[j] + "和" + tnum[j + 1],
        };
        console.log(mount.current);
        if (mount.current)
          setMsg({
            ...tmsg,
          });
        else return;
        await sleep(300);

        if (tnum[j] > tnum[j + 1]) {
          tmsg = {
            ...tmsg,
            sT: tmsg.sT + 1,
            sentence: "交换" + tnum[j] + "和" + tnum[j + 1],
          };
          // console.log(mount.current);
          if (mount.current) setMsg({ ...tmsg });
          else return;

          var tt = tnum[j];
          tnum[j] = tnum[j + 1];
          tnum[j + 1] = tt;

          tt = tmp1[j];
          tmp1[j] = tmp1[j + 1];
          tmp1[j + 1] = tt;

          const t1 = tmp1[j],
            t2 = tmp1[j + 1];

          tmp3[t1] = j;
          tmp3[t2] = j + 1;

          setPos([...tmp3]);
        }
      }
    }
    await sleep(600);
    setColor((val) => 3);
  };

  return (
    <Paper className="Bubblemain" elevation={3}>
      <div className="BubbleInner">
        {pos.map((val, index) => {
          return (
            <Pillar
              number={numbers[val]}
              color={color[index]}
              pos={val}
              height={tnumbers[index]}
            />
          );
        })}
      </div>
      <div
        style={{
          width: "100%",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          marginTop: "20px",
        }}
      >
        <TextField
          // label="数据"
          value={ipt}
          helperText="*请输入英文逗号隔开的正整数"
          size="small"
          onChange={(e) => {
            setIpt(e.target.value);
          }}
        />
        <Box sx={{ marginTop: 4, display: "flex", flexDirection: "row" }}>
          <MyButton loading={isSorting} variant="contained" onClick={change}>
            {isSorting ? "正在排序" : "提交"}
          </MyButton>
          <RandomButton setData={setIpt} loading={isSorting} />
        </Box>
      </div>
    </Paper>
  );
}

/*

0,1,2
0,1,2


1,0,2
1,0,2


1,2,0

2,0,1

2,3,1


2,1,3
1,2,0


*/
